package com.bdq.recommend.infrastructure.config;

import com.bdq.common.entity.common.CommonResult;
import com.bdq.common.exception.ServerException;
import com.bdq.common.exception.ServiceException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author malei
 * @date 2024-05-04 12:19
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServerException.class)
    public CommonResult<Object> handleServerException(ServerException ex) {
        // 使用自定义异常中的code和message
        return CommonResult.error(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public CommonResult<Object> handleServiceException(ServiceException ex) {
        // 使用自定义异常中的code和message
        return CommonResult.error(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult<Object> handleGeneralException(Exception ex) {
        ex.printStackTrace();
        // 对于未预料到的异常，返回通用错误代码
        return CommonResult.error(-1, "Internal server error");
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public CommonResult<Object> argumentVerifyException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return CommonResult.error(-1, fieldError.getDefaultMessage());
    }

    /**
     * 参数绑定异常
     */
    @ExceptionHandler(value = {BindException.class, IllegalArgumentException.class})
    public CommonResult<Object> bindException(Exception ex) {
        ex.printStackTrace();
        return CommonResult.error(-1, ex.getMessage());
    }
}

